package com.course.controller.permission;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.util.Log;
import android.view.View;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import com.baselib.android.utils.UriUtil;
import com.course.android.NewApplication;
import com.course.android.ui.dialog.PositiveDialog;
import com.course.model.SysPermission;

import org.apache.commons.lang.StringUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class PermissionController {

    private static PermissionController manager;

    public static PermissionController getManager() {
        if (manager == null) {
            manager = new PermissionController();
        }
        return manager;
    }

    public static HashMap<Integer, SysPermission> permissionHashMap = new HashMap<>();

    static {
        permissionHashMap.put(PermissionReqCode.REQ_SELECT_ALBUM, new SysPermission(
                PermissionReqCode.REQ_SELECT_ALBUM,
                "申请相机麦克风，储存读写权限",
                "权限允许后，您可以在应用中发送语音消息。",
                new String[]{
                        Manifest.permission.CAMERA,
                        Manifest.permission.RECORD_AUDIO,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                }
        ));
        permissionHashMap.put(PermissionReqCode.REQ_VIDEO, new SysPermission(
                PermissionReqCode.REQ_VIDEO,
                "申请相机麦克风，相机,储存读写权限",
                "权限允许后，您可以在应用中发送语音消息。",
                new String[]{
                        Manifest.permission.CAMERA,
                        Manifest.permission.RECORD_AUDIO,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                }
        ));
    }

    public static Dialog getPersissionDialog(final Activity context, int reqCode) {
        if (permissionHashMap.get(reqCode) == null) {
            return null;
        }
        SysPermission sysPermission = permissionHashMap.get(reqCode);
        return getPersissionDialog(context, sysPermission.getPermissions(), reqCode, sysPermission.getpTitle(), sysPermission.getpDesc());
    }


    public static Dialog getPersissionDialog(final Activity context, final String permission, final int reqCode, String dTitle, String dDesc) {
        if (StringUtils.isBlank(permission)) {
            return null;
        }
        if (grantedPermission(context, permission)) {
            return null;
        }


        PositiveDialog permissionDialog = new PositiveDialog(context);
        permissionDialog.buildTitle(dTitle);
        permissionDialog.buildDesc(dDesc);
        permissionDialog.buildOkName("授权");
        permissionDialog.buildOkClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                requestArrayPermission(context, new String[]{permission}, reqCode);
            }
        });
        return permissionDialog;
    }

    public static Dialog getPersissionDialog(final Activity context, final String[] permissions, final int reqCode, String dTitle, String dDesc) {
        if (permissions == null || permissions.length == 0) {
            return null;
        }
        String[] array = fliterPermission(context, permissions);
        if (array == null || array.length == 0) {
            return null;
        }
        PositiveDialog permissionDialog = new PositiveDialog(context);
        permissionDialog.buildTitle(dTitle);
        permissionDialog.buildDesc(dDesc);
        permissionDialog.buildOkName("授权");
        permissionDialog.buildOkClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                requestArrayPermission(context, permissions, reqCode);
            }
        });
        return permissionDialog;
    }


    public void requestSiglePermission(Activity context, String permission, int reqCode,
                                       PermissionGranteCallback permissionGranteCallback) {
        if (StringUtils.isBlank(permission)) {
            return;
        }
        if (grantedPermission(context, permission)) {
            if (permissionGranteCallback != null) {
                permissionGranteCallback.granted(new String[]{permission}, reqCode);
            }
        }
        ActivityCompat.requestPermissions(context,
                new String[]{
                        permission
                },
                reqCode);
    }

    public static void requestArrayPermission(Activity context, String[] permissions, int reqCode) {
        if (permissions == null || permissions.length == 0) {
            return;
        }
        ActivityCompat.requestPermissions(context,
                permissions,
                reqCode);
    }


    /**
     * 判断权限是否获取
     *
     * @param context
     * @param permission
     * @return
     */
    public static boolean grantedPermission(Context context, String permission) {
        Log.e("aaaa", permission + "--" + ContextCompat.checkSelfPermission(context,
                permission));
        if (ContextCompat.checkSelfPermission(context,
                permission)
                != PackageManager.PERMISSION_GRANTED) {
            return false;
        }


        return true;
    }

    /**
     * 去除已经授权的权限
     *
     * @param context
     * @param permissions
     * @return
     */
    public static String[] fliterPermission(Context context, String[] permissions) {
        if (permissions == null || permissions.length == 0) {
            return new String[]{};
        }
        List<String> items = new ArrayList<>();
        for (String permission : permissions) {
            if (!grantedPermission(context, permission)) {
                items.add(permission);
            }
        }
        String[] array = new String[items.size()];
        items.toArray(array);
        return array;
    }





    public static boolean canRequestPackageInstalls(Context context) {

        if (Build.VERSION.SDK_INT >= 26) {
            return context.getPackageManager().canRequestPackageInstalls();
        }
        return true;
    }


    public static void installApk(Context activity, String path) {
        //   Log.e("下载文件","下载文件安装完成1"+path);
        File f = new File(path);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);


//        intent.setDataAndType(UriUtil.getUriFromPath(YiApplication.getInstance().getContext(),f.getPath()),
//                "application/vnd.android.package-archive");
        // Log.e("下载文件","下载文件安装完成2"+path);

//        try {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            String prider = activity.getPackageName() + ".provider";
            //    Log.e("##","###"+prider);
            Uri contentUri = FileProvider.getUriForFile(activity, prider, f);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(UriUtil.getUriFromPath(NewApplication.getApp().getApplicationContext(), f.getPath()),
                    "application/vnd.android.package-archive");
        }

        // Log.e("下载文件","下载文件安装完成3"+path);

        activity.startActivity(intent);
//
//        }catch (Exception e){
//              Log.e("下载文件","下载文件安装完成3"+e.getLocalizedMessage());
//        }
    }

    public static boolean requestPermissions(Activity activity, String[] permissions, int requestCode) {
        if (permissions == null || permissions.length == 0) {
            return true;
        }
        List<String> permission = new ArrayList<>();
        for (String per : permissions) {
            if (!grantedPermission(activity, per)) {
                permission.add(per);
            }
        }

        if (permission.size() == 0) {
            return true;
        }

        String[] array = new String[permission.size()];
        permission.toArray(array);
        ActivityCompat.requestPermissions(activity,
                array,
                requestCode);
        return false;
    }

}
